package cn.lg.soar.flow.api.model.node;

import cn.lg.soar.common.util.data.DataUtil;
import cn.lg.soar.flow.api.utils.XmlUtils;
import com.fasterxml.jackson.annotation.JsonProperty;

import java.io.Serializable;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
public class StartNode extends UserNode implements Node, Serializable {

    // Getters and Setters
    @JsonProperty("type")
    @Override
    public String getType() { return "start"; }

    @Override
    public String toXmlString() {
        StringBuilder sb = new StringBuilder();

        // 可选：添加注释
        sb.append("<!-- Initiator Task: ").append(name).append(" -->\n");
        // 开始构建 userTask
        sb.append("<userTask id=\"").append(key).append("\" name=\"").append(XmlUtils.escapeXml(name)).append("\"");

        // === 关键：将任务分配给流程发起人 ===
        // Flowable 和 Camunda 都支持 ${initiator} 或 ${execution.startUserId} 等变量
        sb.append(" flowable:assignee=\"${initiator}\"");
//        XmlUtils.appendAttribute(sb, "flowable:formKey", formKey); // 表单key

        // 可选：任务超时时间（例如：72 小时内必须提交）
        /*if (dueDate != null && dueDate > 0) {
            String dueDateExpr = "#{new java.util.Date().getTime() + (" + dueDate + " * 60 * 60 * 1000)}";
            sb.append(" flowable:dueDate=\"").append(escapeXml(dueDateExpr)).append("\"");
        }*/

        // 可选：任务优先级
       /* if (priority != null) {
            sb.append(" flowable:priority=\"").append(priority).append("\"");
        }*/
        sb.append(" >");
        // 添加监听器
        if (DataUtil.isValuable(nodeListeners) || DataUtil.isValuable(processListeners)) {
            sb.append("<extensionElements>");
            if (DataUtil.isValuable(nodeListeners)) {
                for (NodeListener x : nodeListeners) {
                    sb.append("<flowable:taskListener event=\"").append(x.getEvent().name()).append("\" ")
                            .append(Boolean.TRUE.equals(x.getIsExpression()) ? "expression" : "class")
                            .append("=\"").append(XmlUtils.escapeXml(x.getValue())).append("\" />\n");
                }
            }
            if (DataUtil.isValuable(processListeners)) {
                for (ProcessListener x : processListeners) {
                    sb.append("<flowable:executionListener event=\"").append(x.getEvent()).append("\" ")
                            .append(Boolean.TRUE.equals(x.getIsExpression()) ? "expression" : "class")
                            .append("=\"").append(XmlUtils.escapeXml(x.getValue())).append("\" />\n");
                }
            }
            sb.append("</extensionElements>\n");
        }
        sb.append("</userTask>\n");

        return sb.toString();
    }
}